package com.systop.asset.config.handle;

import com.systop.asset.entity.RestResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.Cookie;
import java.io.IOException;

@Component
public class CustomAuthEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

        // 1. 清除 SecurityContext
        SecurityContextHolder.clearContext();

        // 2. 清除 Session（如果存在）
        if (request.getSession(false) != null) {
            request.getSession().invalidate();
        }

        // 3. 删除 JSESSIONID Cookie
        Cookie cookie = new Cookie("JSESSIONID", null);
        cookie.setPath("/");                  // 匹配路径
        cookie.setMaxAge(0);                  // 立即过期
        cookie.setHttpOnly(true);             // 匹配原始设置
        cookie.setSecure(request.isSecure()); // 根据当前请求是否使用 HTTPS
        response.addCookie(cookie);           // 添加到响应头

        // 4. 返回 401 响应
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        RestResponse<?> errorResponse = RestResponse.failure(401, "用户未登录");
        response.getWriter().write(errorResponse.asJsonString());
    }


}

